package com.news.news.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.news.news.dao.AdminDao;
import com.news.news.dao.RoleDao;
import com.news.news.modle.Admin;
import com.news.news.modle.Menu;
import com.news.news.modle.Role;
import com.news.news.util.JWTUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * Created by 罗铠威 on 2023/8/29 16:21
 * type:
 */
@Service
@Transactional
public class RoleService {

    @Resource
    RoleDao roleDao;

    public PageInfo<Role> adminList(Role role){
        PageHelper.startPage(role.getPageNum(),role.getPageSize());
        ArrayList<Role> roles = roleDao.roleList(role);
//        System.out.println(roles);
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        return pageInfo;
    }

    public ArrayList<Menu> findMenus() {
        return roleDao.findMenus();

    }

    public void saveRole(Role role, String token) {
        role.setAdminid(JWTUtil.getTokenInfo(token).getClaim("id").asInt());
        //保存角色信息并返回id
        roleDao.saveRole(role);
        //保存角色与菜单关系表
        if(role.getMenuList().length!=0){
            for (Integer menuid : role.getMenuList()) {
                roleDao.addRoleMenu(role.getId(),menuid);
            }
        }

    }

    public void updateRole(Role role,String token) {
        role.setAdminid(JWTUtil.getTokenInfo(token).getClaim("id").asInt());
        roleDao.updateRole(role);//存储角色信息
        //将角色与菜单的关系删除
            roleDao.deleteRoleMenu(role.getId());
        //添加新的角色关系
        if(role.getMenuList().length!=0){
            for (Integer menuid : role.getMenuList()) {
                roleDao.addRoleMenu(role.getId(),menuid);
            }
        }
    }

    public Role findRoleById(Integer id) {
     Role role= roleDao.findRoleById(id);
     if(role.getMenus()!=null){
         Integer[] a=new Integer[role.getMenus().size()];
         for (int i=0;i<a.length;i++) {
             a[i]= role.getMenus().get(i).getId();
         }
         role.setMenuList(a);
     }
     return role;
    }

    public void deleteRole(Integer id) {
        roleDao.deleteRoleMenu(id);
        roleDao.deleteRole(id);
    }
}
